package cc.vicp.djx314.starfood.web.personnel.dish;

import java.io.File;
import java.io.IOException;
import java.sql.Time;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.servlet.ModelAndView;

import cc.vicp.djx314.starfood.domain.dish.Dish;
import cc.vicp.djx314.starfood.service.dishes.DishService;
import cc.vicp.djx314.starfood.util.time.SqlTimeEditor;
import cc.vicp.djx314.starfood.web.user.UserInfoController;

@Controller
public class DishCreateController {
	public static final Logger logger = LoggerFactory.getLogger(DishCreateController.class);
	
	@Autowired
	DishService dishService;
	
	@RequestMapping(value = "/personnel/dish/create", method = RequestMethod.POST)
	public ModelAndView createDish(@RequestParam(value = "dishImgPath") String dishImgPath,
			@RequestBody Dish dish, HttpServletRequest request) {
		boolean success = false;
		try {
			ServletContext context = request.getSession().getServletContext();
			Resource resource = new ServletContextResource(context, "/img/dishimgtemp/" + dishImgPath);
			File dishImgFile = resource.getFile();
			byte[] dishImg = FileCopyUtils.copyToByteArray(dishImgFile);
			dishService.createDish(dish, dishImg);
			success = true;
		} catch (IOException e1) {
			logger.info("菜式图像文件找不到", e1);
		} catch (Exception e2) {
			logger.error("创建菜式发生未知错误", e2);
		}
		ModelAndView model = new ModelAndView("jsontournamenttemplate");
		model.addObject("dish", dish);
		model.addObject("success", success);
		return model;
	}
}